import React,{ useReducer, useEffect } from "react";

let getValue = ()=>{return {}}
function Redux(props){
    let { children, name, saveMode, store } = props
    const [state, dispatch] = useReducer((state, action)=>{
        let { key, value, type } = action
        switch (type) {
            case 'create':
                let obj = {...state}
                let index = Object.keys(state).findIndex((val)=>val === key)
                if(index === -1){
                    obj[key] = value 
                    return {...obj}
                }
                console.log('重复请使用action.upDate')
                return {...obj}
            case 'delete':
                delete state[key]
                return {...state}
            case 'upDate':
                state[key] = value
                return{...state}
            default:
                // 支持查询单个和多个
                if(typeof key === 'string') {
                    return { }
                }
                if(Array.isArray(key)){
                    return key.map(val=>state[val])
                }
                //如果没有传入 返回全部
                return {...state}
        }
    },{}) // 初始值 {} 
    useEffect(()=>{
        console.log('全局状态:',state)

        getValue = (key) => {
            if(key){
                return getValueByKey( state, key )
            }
            return state
        }
        if(saveMode === 'local'){
            localStorage.setItem(name, JSON.stringify(state))
        }
        if(saveMode === 'session'){
            sessionStorage.setItem(name, JSON.stringify(state))
        } 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    },[state])
    return(
        <store.Provider
            value = {{state, dispatch}}
        >
            {children}
        </store.Provider>
    )    
}

function getValueByKey ( state, key ) {
    return state[key]
}
Redux.defaultProps = {
    name:'redux',
    saveMode:'session'
}
export{
    getValue
}
export default Redux